﻿// ------------------------------------------------------------------------------------------------
//  <copyright file="ParallelHelper.cs" company="Iveely">
//    Copyright (c) Iveely Liu.  All rights reserved.
//  </copyright>
//  
//  <Create Time>
//    03/02/2013 21:59 
//  </Create Time>
//  
//  <contact owner>
//    liufanping@iveely.com 
//  </contact owner>
//  -----------------------------------------------------------------------------------------------

#region

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

#endregion

namespace IveelySE.Common
{
    /// <summary>
    ///   并行执行帮助类
    /// </summary>
    public static class ParallelHelper
    {
        private static readonly ParallelOptions NoParallelOptions = new ParallelOptions();

        public static void InParallelWhile(this Action<ParallelLoopState> action, bool condition,
                                           ParallelOptions options = null)
        {
            if(options == null) options = NoParallelOptions;

            Parallel.ForEach(IterateForever(), options,
                             (ignored, loopState) =>
                                 {
                                     if(!condition)
                                     {
                                         loopState.Stop();
                                     }
                                     else
                                     {
                                         action(loopState);
                                     }
                                 });
        }

        private static IEnumerable<bool> IterateForever()
        {
            while(true)
            {
                yield return true;
            }
        }
    }
}